package com.lnb.controller;

import java.util.HashMap;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lnb.config.JwtConfig;
import com.lnb.entity.Users;
import com.lnb.service.IUsersService;



@RestController
public class LoginController {
	@Resource
	private JwtConfig jwtConfig;

	@Autowired
	IUsersService iUsersService;

	/*
	 * 返参格式 { "userName": "ID123", "token":
	 * "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMSIsImlhdCI6MTU4ODg2MDE0MCwiZXhwIjoxNTg4ODYzNzQwfQ.pwpuI-E2xskyqqzjeWe_DU-ASIyyrwbKswX2da_GC9e2ucZ0xfGSbXdmHQWIZ5ITJXrZLgTtWNBg_ceDivkqtA"
	 * }
	 */
	// 拦截器直接放行，返回Token
	@PostMapping("/login")
	public Object login(@RequestParam("loginName") String loginName, @RequestParam("password") String password) {
		Map<String, Object> result = new HashMap<>();

		// 数据源校验
		QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("login_name", loginName).eq("password", password);
		Users one = iUsersService.getOne(queryWrapper, false);
		if (one == null) { //没找到
			result.put("code", 501);
			result.put("msg", "登录失败，用户名或密码错误");
		} else {  //找到了
			String token = jwtConfig.getToken(loginName + password);
			if (!StringUtils.isEmpty(token)) {
				result.put("token", token);
			}
			result.put("data", one);
			result.put("code", 0);
		}
		return result;
	}

}
